package com.springboot.chatroom.controller;


import com.springboot.chatroom.model.MessageSession;
import com.springboot.chatroom.model.MessageSessionUserItem;
import com.springboot.chatroom.model.User;
import com.springboot.chatroom.service.MessageService;
import com.springboot.chatroom.service.MessageSessionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-04-14
 * Time: 10:06
 */
@Slf4j
@RestController
@RequestMapping("/session")
public class MessageSessionController {

    @Autowired
    private MessageSessionService messageSessionService;

    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "/sessionList", method = RequestMethod.GET)
    public Object getMessageSessionList(HttpServletRequest request) {
        List<MessageSession> messageSessionList = new ArrayList<>();
        // 1、从请求中获取session信息，并从session中获取userId
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.info("[getMessageSessionList] 用户并未登录...");
            return messageSessionList; // 返回的是空对象
        }
        User user = (User)session.getAttribute("user");
        if (user == null) {
            log.info("[getMessageSessionList] 用户并未登录...");
            return messageSessionList; // 返回的是空对象
        }
        // 2、根据userId查询当前用户所属的会话，返回sessionId集合
        int userId = user.getUserId();
        List<Integer> sessionList = messageSessionService.getSessionIdsByUserId(userId);
        // 3、根据sessionId查询当前会话中，存在哪些用户，并返回用户信息集合（除去自己）
        // 4、对上述查询的结果进行封装，返回的是MessageSession数组
        // 由于sessionId是存储在List集合中，因此得一个一个的去遍历集合
        for (Integer sessionId : sessionList) {
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            messageSession.setFriends(messageSessionService.getFriendsBySessionId(sessionId, userId));
            String message = messageService.getLastMessageBySessionId(sessionId);
            // 可能会话刚创建，并不存在消息
            if (message == null) {
                messageSession.setLastMessage("");
            } else {
                messageSession.setLastMessage(message);
            }
            // 将会话信息添加到会话列表中
            messageSessionList.add(messageSession);
        }
        return messageSessionList;
    }

    @Transactional // 保证该方法执行时，要么全部成功，要么全部失败，也就是事务
    @RequestMapping(value = "/addSession",method = RequestMethod.POST)
    public Object addMessageSession(Integer toUserId, HttpServletRequest request) {
        // 1、判断参数是否合法且有效
        if (toUserId == null || toUserId <= 0) {
            log.info("[addMessageSession] toUserId无效...");
            return new Object();
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.info("[addMessageSession] 用户并未登录...");
            return new Object();
        }
        User user = (User)session.getAttribute("user");
        if (user == null) {
            log.info("[addMessageSession] 用户并未登录...");
            return new Object();
        }
        // 2、创建新会话、绑定会话与用户的关系
        MessageSession messageSession = new MessageSession(); // 保存会话的自增主键
        Integer result = messageSessionService.addMessageSession(messageSession);
        if (result <= 0) {
            log.info("[addMessageSession] 新建会话失败...");
            return new Object();
        }
        // 绑定会话与用户之间的关系
        // 绑定当前用户与会话的关系
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setUserId(user.getUserId());
        item1.setSessionId(messageSession.getSessionId());
        result = messageSessionService.addMessageSessionUserItem(item1);
        if (result <= 0) {
            log.info("[addMessageSession] 新建会话失败...");
            return new Object();
        }
        // 绑定好友与会话的关系
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setUserId(toUserId);
        item2.setSessionId(messageSession.getSessionId());
        result = messageSessionService.addMessageSessionUserItem(item2);
        if (result <= 0) {
            log.info("[addMessageSession] 新建会话失败...");
            return new Object();
        }
        log.info("[addMessageSession] 新建会话成功...");
        // 返回会话Id
        return messageSession.getSessionId();
    }
}
